<template>
  <div id="contestManageView">
    <a-card title="比赛管理">
      <template #extra>
        <a-button type="primary" @click="createContest"> 创建比赛 </a-button>
      </template>

      <a-table
        :columns="columns"
        :data="contestList"
        :pagination="{
          showTotal: true,
          pageSize: searchParams.pageSize,
          current: searchParams.current,
          total,
        }"
        @page-change="onPageChange"
      >
        <template #status="{ record }">
          <a-tag :color="getStatusColor(record.status)">
            {{ getStatusText(record.status) }}
          </a-tag>
        </template>
        <template #isPublic="{ record }">
          <a-tag :color="record.isPublic ? 'green' : 'orange'">
            {{ record.isPublic ? "公开" : "私有" }}
          </a-tag>
        </template>
        <template #actions="{ record }">
          <a-space>
            <a-button size="small" @click="editContest(record)">
              编辑
            </a-button>
            <a-button size="small" @click="manageProblems(record)">
              题目管理
            </a-button>
            <a-button
              size="small"
              status="danger"
              @click="deleteContest(record)"
            >
              删除
            </a-button>
          </a-space>
        </template>
      </a-table>
    </a-card>

    <!-- 创建/编辑比赛对话框 -->
    <a-modal
      v-model:visible="modalVisible"
      :title="editingContest ? '编辑比赛' : '创建比赛'"
      width="800px"
      @ok="handleSubmit"
      @cancel="modalVisible = false"
    >
      <a-form :model="form" layout="vertical">
        <a-form-item label="比赛标题" required>
          <a-input v-model="form.title" placeholder="请输入比赛标题" />
        </a-form-item>
        <a-form-item label="比赛描述">
          <a-textarea
            v-model="form.description"
            placeholder="请输入比赛描述"
            :rows="3"
          />
        </a-form-item>
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="开始时间" required>
              <a-date-picker
                v-model="form.startTime"
                show-time
                placeholder="选择开始时间"
                style="width: 100%"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="结束时间" required>
              <a-date-picker
                v-model="form.endTime"
                show-time
                placeholder="选择结束时间"
                style="width: 100%"
              />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="比赛类型">
              <a-select v-model="form.ruleType" placeholder="选择比赛类型">
                <a-option :value="0">ACM</a-option>
                <a-option :value="1">OI</a-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="访问权限">
              <a-switch
                v-model="form.isPublic"
                checked-children="公开"
                un-checked-children="私有"
              />
            </a-form-item>
          </a-col>
        </a-row>
        <a-form-item v-if="!form.isPublic" label="访问密码">
          <a-input v-model="form.password" placeholder="请输入访问密码" />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref } from "vue";
import { useRouter } from "vue-router";
import message from "@arco-design/web-vue/es/message";
import { ContestControllerService } from "../../generated";
import type { Contest } from "../../generated";

const router = useRouter();

// 数据
const contestList = ref<Contest[]>([]);
const total = ref(0);
const searchParams = ref({
  pageSize: 10,
  current: 1,
});

// 表单相关
const modalVisible = ref(false);
const editingContest = ref<Contest | null>(null);
const form = ref({
  title: "",
  description: "",
  startTime: null,
  endTime: null,
  ruleType: 0,
  isPublic: true,
  password: "",
});

// 表格列定义
const columns = [
  {
    title: "ID",
    dataIndex: "id",
    width: 80,
  },
  {
    title: "标题",
    dataIndex: "title",
  },
  {
    title: "状态",
    slotName: "status",
    width: 100,
  },
  {
    title: "访问权限",
    slotName: "isPublic",
    width: 100,
  },
  {
    title: "开始时间",
    dataIndex: "startTime",
    width: 180,
  },
  {
    title: "结束时间",
    dataIndex: "endTime",
    width: 180,
  },
  {
    title: "操作",
    slotName: "actions",
    width: 200,
  },
];

// 加载比赛列表
const loadData = async () => {
  try {
    const res = await ContestControllerService.getContestListUsingGet(
      searchParams.value.current,
      searchParams.value.pageSize
    );
    if (res.code === 0) {
      contestList.value = res.data?.records || [];
      total.value = res.data?.total || 0;
    } else {
      message.error("加载失败，" + res.message);
    }
  } catch (error) {
    message.error("加载失败");
  }
};

// 分页处理
const onPageChange = (page: number) => {
  searchParams.value.current = page;
  loadData();
};

// 状态处理
const getStatusText = (status: number) => {
  const statusMap = {
    0: "未开始",
    1: "进行中",
    2: "已结束",
  };
  return statusMap[status as keyof typeof statusMap] || "未知";
};

const getStatusColor = (status: number) => {
  const colorMap = {
    0: "blue",
    1: "green",
    2: "gray",
  };
  return colorMap[status as keyof typeof colorMap] || "default";
};

// 创建比赛
const createContest = () => {
  editingContest.value = null;
  form.value = {
    title: "",
    description: "",
    startTime: null,
    endTime: null,
    ruleType: 0,
    isPublic: true,
    password: "",
  };
  modalVisible.value = true;
};

// 编辑比赛
const editContest = (contest: Contest) => {
  editingContest.value = contest;
  form.value = {
    title: contest.title || "",
    description: contest.description || "",
    startTime: contest.startTime ? new Date(contest.startTime) : null,
    endTime: contest.endTime ? new Date(contest.endTime) : null,
    ruleType: contest.ruleType || 0,
    isPublic: contest.isPublic || true,
    password: contest.password || "",
  };
  modalVisible.value = true;
};

// 提交表单
const handleSubmit = async () => {
  try {
    const contestData = {
      ...form.value,
      startTime: form.value.startTime?.toISOString(),
      endTime: form.value.endTime?.toISOString(),
    };

    let res;
    if (editingContest.value) {
      res = await ContestControllerService.updateContestUsingPut(
        editingContest.value.id!,
        contestData
      );
    } else {
      res = await ContestControllerService.createContestUsingPost(contestData);
    }

    if (res.code === 0) {
      message.success(editingContest.value ? "更新成功" : "创建成功");
      modalVisible.value = false;
      loadData();
    } else {
      message.error("操作失败，" + res.message);
    }
  } catch (error) {
    message.error("操作失败");
  }
};

// 删除比赛
const deleteContest = async (contest: Contest) => {
  try {
    const res = await ContestControllerService.deleteContestUsingDelete(
      contest.id!
    );
    if (res.code === 0) {
      message.success("删除成功");
      loadData();
    } else {
      message.error("删除失败，" + res.message);
    }
  } catch (error) {
    message.error("删除失败");
  }
};

// 管理题目
const manageProblems = (contest: Contest) => {
  router.push({
    path: `/contest/${contest.id}/problems/manage`,
  });
};

// 页面加载
onMounted(() => {
  loadData();
});
</script>

<style scoped>
#contestManageView {
  max-width: 1400px;
  margin: 0 auto;
  padding: 16px;
}
</style>
